package com.example.hcd.datamanage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.widget.ImageView;

public class UserInfo {

	private static UserInfo sInfor;

	public static UserInfo getUserInfor() {
        if (sInfor == null) {
            sInfor = new UserInfo();
        }
        return sInfor;
    }
	//用戶id
	private String id="";
	//用戶名
	private String username="";
	//真實姓名
	private String name="";
	//密碼
	private String password="";
	//性別
	private int gender;
	//公司ID
	private String companyId="";
	//部門ID
	private String departmentId="";
	//角色ID
	private String userRolesid="";
	//手机号码
	private String mobileNumber="";
	//办公电话
	private String office_tel="";
	//常用邮箱
	private String email="";
	//生日
	private String birthday="";
	//工作传真
	private String office_fax="";
	//QQ号
	private String qq="";
	//家庭住址
	private String home_address="";
	//家庭邮编
	private String zip_code="";
	//家庭号码
	private String home_tel="";
	
	private Bitmap mBitmap;
	//头像是否更换
	private boolean photoChange;
	//
	private String cookie;
	//部门名称
	private String departmnet="";
	//上次密码修改时间
	private String lastModifyPdTime="";
	//是否总公司
	private String isHead="";
	
	//公司名称
	private String companyName="";
	
	//是否在前台
	public boolean isActive;

	public boolean isLogin;

	public boolean isLogin() {
		return isLogin;
	}

	public void setIsLogin(boolean isLogin) {
		this.isLogin = isLogin;
	}

	//是否调用了照相机等
	public boolean isUsePhoto;
	
	//包含的权限角色
	private ArrayList<RoleInfoData> roleInfoDatas = new ArrayList<RoleInfoData>();

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getGender() {
		if(gender == 1)
		{
			return "男";
		}else
		{
			return "女";
		}
	
	}
	
	public boolean  isShenZhen()
	{
		if(companyName.contains("深圳"))
		{
			return true;
		}
		
		return false;
	}

	public void setGender(int gender) {
		this.gender = gender;
	}

	public String getCompanyId() {
		return companyId;
	}

	public void setCompanyId(String companyId) {
		this.companyId = companyId;
	}

	public String getDepartmentId() {
		return departmentId;
	}

	public void setDepartmentId(String departmentId) {
		this.departmentId = departmentId;
	}

	public String getUserRolesid() {
		return userRolesid;
	}

	public void setUserRolesid(String userRolesid) {
		this.userRolesid = userRolesid;
	}

	public String getMobileNumber() {
		return mobileNumber;
	}

	public void setMobileNumber(String mobileNumber) {
		this.mobileNumber = mobileNumber;
	}

	public String getOffice_tel() {
		return office_tel;
	}

	public void setOffice_tel(String office_tel) {
		this.office_tel = office_tel;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getBirthday(boolean isneedGeshi) {
		if(birthday==null||birthday.equals(""))
		{
			return "未填写";
		}

		if(isneedGeshi)
		{
			try {
				SimpleDateFormat mFormat= new SimpleDateFormat("yyyy-MM-dd");
				//继续转换得到秒数的long型  
				Date time = mFormat.parse(birthday);
				
				long dtime = time.getTime();
				return ""+dtime;
			} catch (Exception e) {
				return "生日获取错误";
			}
			
		}else
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
		if(birthday==null || birthday.equals(""))
		{
			birthday = "请选择生日";
		}
	}

	public String getOffice_fax() {
		return office_fax;
	}

	public void setOffice_fax(String office_fax) {
		this.office_fax = office_fax;
	}

	public String getQq() {
		return qq;
	}

	public void setQq(String qq) {
		this.qq = qq;
	}

	public String getHome_address() {
		return home_address;
	}

	public void setHome_address(String home_address) {
		this.home_address = home_address;
	}

	public String getZip_code() {
		return zip_code;
	}

	public void setZip_code(String zip_code) {
		this.zip_code = zip_code;
	}

	public String getHome_tel() {
		return home_tel;
	}

	public void setHome_tel(String home_tel) {
		this.home_tel = home_tel;
	}

	//MD5加密
	public String MD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");

        } catch (Exception e)

        {
            e.printStackTrace();
            return "";
        }
        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }
	
	public void loadHeaderPhotos(ImageView imageView, Bitmap def) {
        if (def != null) {
            setmBitmap(def);
            imageView.setImageBitmap(toRoundBitmap(def));
            System.out.println("图片替换了");
            
        } else {
        	//Bitmap bitmap = BitmapFactory.decodeResource(MenuActivity.mContext.getResources(), R.drawable.mrtx);
            imageView.setImageResource(R.drawable.mrtx);
        	//imageView.setImageBitmap(toRoundBitmap(bitmap));
            System.out.println("图片没替换");
        }
    }

	//设置头像
	/** 
     * 转换图片成圆形 
     *  
     * @param bitmap 
     *            传入Bitmap对象 
     * @return 
     */  
    public Bitmap toRoundBitmap(Bitmap bitmap) {  
        int width = bitmap.getWidth();  
        int height = bitmap.getHeight();  
        float roundPx;  
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;  
        if (width <= height) {  
            roundPx = width / 2;  
            left = 0;  
            top = 0;  
            right = width;  
            bottom = width;  
            height = width;  
            dst_left = 0;  
            dst_top = 0;  
            dst_right = width;  
            dst_bottom = width;  
        } else {  
            roundPx = height / 2;  
            float clip = (width - height) / 2;  
            left = clip;  
            right = width - clip;  
            top = 0;  
            bottom = height;  
            width = height;  
            dst_left = 0;  
            dst_top = 0;  
            dst_right = height;  
            dst_bottom = height;  
        }  
  
        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);  
        Canvas canvas = new Canvas(output);  
  
        final int color = 0xff424242;  
        final Paint paint = new Paint();  
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);  
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);  
        final RectF rectF = new RectF(dst);  
  
        paint.setAntiAlias(true);// 设置画笔无锯齿  
  
        canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas  
        paint.setColor(color);  
  
        // 以下有两种方法画圆,drawRounRect和drawCircle  
        // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);// 画圆角矩形，第一个参数为图形显示区域，第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。  
        canvas.drawCircle(roundPx, roundPx, roundPx, paint);  
  
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452  
        canvas.drawBitmap(bitmap, src, dst, paint); //以Mode.SRC_IN模式合并bitmap和已经draw了的Circle  
          
        return output;  
    }
	

	
	public void setPhotoChange(boolean f) {
        photoChange = f;
    }

	public String getCookie() {
		return cookie;
	}

	public void setCookie(String cookie) {
		this.cookie = cookie;
	}

	public Bitmap getmBitmap() {
		return mBitmap;
	}

	public void setmBitmap(Bitmap mBitmap) {
		this.mBitmap = mBitmap;
	}

	public String getDepartmnet() {
		return departmnet;
	}

	public void setDepartmnet(String departmnet) {
		this.departmnet = departmnet;
	}

	public String getLastModifyPdTime() {
		try {
			SimpleDateFormat mFormat= new SimpleDateFormat("yyyy-MM-dd");
			//继续转换得到秒数的long型  

			return mFormat.format(new Date(Long.parseLong(lastModifyPdTime)));
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		
		return lastModifyPdTime;
	}

	public void setLastModifyPdTime(String lastModifyPdTime) {
		this.lastModifyPdTime = lastModifyPdTime;
	}

	public String getIsHead() {
		return isHead;
	}

	public void setIsHead(String isHead) {
		this.isHead = isHead;
	}

	public String getCompanyName() {
		return companyName;
	}

	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}
	
	public void updateUserInfo()
	{
		LoadUserInfo load = new LoadUserInfo();
		load.execute();
		
	}
	
	public ArrayList<RoleInfoData> getRoleInfoDatas() {
		return roleInfoDatas;
	}

	public void setRoleInfoDatas(ArrayList<RoleInfoData> roleInfoDatas) {
		this.roleInfoDatas = roleInfoDatas;
	}

	private class LoadUserInfo extends AsyncTask<String, Integer, String> {

		private final String CODE = "code";
		private DefaultHttpClient mHttpClient;

		@Override
		protected void onPreExecute() {

			mHttpClient = new DefaultHttpClient();
		}

		public void cancel() {

			if (mHttpClient != null) {
				mHttpClient.getConnectionManager().shutdown();
			}
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {			
				response = LinkHelp.post(URLS.getCurrentUser(), null, false);

				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						reader.close();
						result = sb.toString();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
        protected void onPostExecute(String result) {

            int errorId = -1;
            if (TextUtils.isEmpty(result)) {
                errorId = R.string.dialog_load_fail_network;
            } else {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(result);
                    if (jsonObject.isNull(CODE)) {
                        //String status = jsonObject.getString("status");
                        UserInfo info = UserInfo.getUserInfor();
                        //if (status.equals("success")) {
                            //加载用户信息
                            {
                            	JSONObject useobject = jsonObject.getJSONObject("userObject");
                            	String id = useobject.getString("id");
                            	String name = useobject.getString("name");
                            	info.setDepartmnet(useobject.getString("department"));
                            	info.setName(name);
                            	info.setPassword(useobject.getString("passWord"));
                            	info.setBirthday(useobject.getString("birthday"));
                            	info.setZip_code(useobject.getString("zip_code"));
                            	info.setLastModifyPdTime(""+useobject.getLong("lastModifyPdTime"));
                            	info.setIsHead(useobject.getString("isHead"));
                            	info.setHome_tel(useobject.getString("home_tel"));
                            	info.setOffice_fax(useobject.getString("office_fax"));
                            	info.setEmail(useobject.getString("emailAddress"));
                            	info.setOffice_tel(useobject.getString("officeTel"));
                            	info.setCompanyName(useobject.getString("companyName"));
                            	info.setPassword(useobject.getString("passWord"));
                            	info.setHome_address(useobject.getString("home_address"));
                            	info.setQq(useobject.isNull("QQ")?"":useobject.getString("QQ"));
                            	info.setUsername(useobject.getString("userName"));
                            	info.setGender(useobject.getInt("gender"));
                            	info.setDepartmentId(useobject.getString("departmentId"));
                            	info.setCompanyId(useobject.getString("companyId"));
                            	info.setMobileNumber(useobject.getString("mobileNumber"));
	
                            //}
                                
                            //return;
                        } 
                        
                    }}  
                catch (JSONException e) {
                    e.printStackTrace();
                }
            }
		}
           
    }
	//是否有管理员权限
	public boolean ishaveCode()
	{
		for(int i=0;i<roleInfoDatas.size();i++)
		{
			String role_code= roleInfoDatas.get(i).getRole_code();
			if(role_code.equals("admin")||role_code.equals("hr"))
			{
				return true;
			}
		}
		return false;
	}
	
	
}
